const { getToken } = require('./jwt');
const { db } = require('./database');

/**
 * 是否登入
 *
 * @function 用来判断用户是否登入，拦截请求，作为请求前中间件
 * @param {string} name 管理员还是普通用户
 * @returns 响应请求
 */
const GenerateAuthMiddle = (name) => {
	return async (req, res, next) => {
		//解析token获取用户信息
		const token = req.headers['authorization'];
		const payload = getToken(token);
		// 获取用户id
		const userId = payload?.userId;
		if (!userId) {
			return res.status(401).send({ success: false, message: '会话过期,用户尚未登入!' });
		}
		// 为以后获取用户信息方便，将用户信息保存在 req.user 上。
		req.user = await db.findOne(`select * from ${name} where id = ?`, [userId]);
		next();
	};
};

/**
 * 是否拥有权限 super admin guest
 *
 * @function 用来鉴权，拦截请求，作为请求前中间件
 * @param  {...string} role 不满足权限数组,会被拦截的角色
 * @returns 响应请求
 */
const Authentication = (...role) => {
	return async (req, res, next) => {
		if (role.length === 0) return res.send({ success: false, message: '权限不足,请联系管理员！' });
		// 从请求头部获得 token
		const token = req.headers['authorization'];
		const payload = getToken(token);
		// 获取用户id
		const userId = payload?.userId || req.session?.userId;
		const user = await db.findOne(`select * from managers where id = ?`, [userId]);
		for (let item of role) {
			if (user.role === item) {
				return res.send({
					success: false,
					message: '权限不足,请联系管理员！'
				});
			}
		}
		next();
	};
};

const ManagerAuth = GenerateAuthMiddle('managers'),
	CustomerAuth = GenerateAuthMiddle('customers');

module.exports = { ManagerAuth, CustomerAuth, Authentication };
